package util

import (
	"crypto/cipher"
	"crypto/des"
	"crypto/md5"
	"encoding/hex"
	"fmt"
)

var defaultKey = []byte("LocalS3X")

func EncryptByMD5(str string) string {
	hash := md5.Sum(StringToBytes(str))
	return hex.EncodeToString(hash[:])
}

func EncryptByDES(data string) (string, error) {
	plaintext := StringToBytes(data)

	block, err := des.NewCipher(defaultKey)
	if err != nil {
		return "", fmt.Errorf("创建加密块失败：%s", err.Error())
	}

	bs := block.BlockSize()
	padText := make([]byte, bs+len(plaintext))
	copy(padText[bs:], plaintext)

	iv := make([]byte, bs)

	mode := cipher.NewCBCEncrypter(block, iv)
	mode.CryptBlocks(padText[bs:], padText[bs:])

	return hex.EncodeToString(padText[bs:]), nil
}

func DecryptByDES(data string) (string, error) {
	ciphertext, err := hex.DecodeString(data)
	if err != nil {
		return "", fmt.Errorf("解码密文失败：%s", err.Error())
	}

	block, err := des.NewCipher(defaultKey)
	if err != nil {
		return "", fmt.Errorf("创建加密块失败：%s", err.Error())
	}

	bs := block.BlockSize()

	iv := make([]byte, bs)

	mode := cipher.NewCBCDecrypter(block, iv)
	mode.CryptBlocks(ciphertext, ciphertext)

	// 去除填充
	padding := int(ciphertext[len(ciphertext)-1])
	plaintext := ciphertext[:len(ciphertext)-padding]

	return BytesToString(plaintext), nil
}
